package joyson.email.service.impl;

import com.sun.mail.util.MailSSLSocketFactory;
import joyson.email.constant.MailConstant;
import joyson.email.properties.EmailProperties;
import joyson.email.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Map;
import java.util.Properties;

/**
 * @description:
 * @Author ke
 * @Date 2024/5/18 12:55
 */
@Service
public class SendEmailServiceImpl implements SendEmailService {

    String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();

    @Autowired
    private EmailProperties emailProperties;

    @Override
    public void send(Map<String, String> params) {

        try {
            //1.配置信息
            Properties prop = new Properties();
            prop.setProperty(MailConstant.MAIL_HOST, emailProperties.getHost());
            prop.setProperty(MailConstant.MAIL_PORT, emailProperties.getPort());
            prop.setProperty(MailConstant.MAIL_PROTOCOL, emailProperties.getProtocol());
            prop.setProperty(MailConstant.MAIL_AUTH, emailProperties.getAuth());
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put(MailConstant.MAIL_SSL_ENABLE, "true");
            prop.put(MailConstant.MAIL_SSL_SOCKET, sf);


            //2 创建定义整个应用程序所需的环境信息的 Session对象
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emailProperties.getMail(), emailProperties.getAuthCode());
                }
            });
            //3 通过session得到transport 对象
            Transport ts = session.getTransport();
            //4 使用邮件的用户名和授权码连接上邮件服务器
            ts.connect(emailProperties.getHost(), emailProperties.getMail(), emailProperties.getAuthCode());

            //5 创建邮件
            MimeMessage message = new MimeMessage(session);

            //指明发件人
            message.setFrom(new InternetAddress(emailProperties.getMail()));

            //指明收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(params.get("to")));

            //主题
            message.setSubject(params.get("subject"));

            //图片部分
            MimeBodyPart image = new MimeBodyPart();
            DataHandler dh = new DataHandler(new FileDataSource(params.get("picture")));
            image.setDataHandler(dh);
            image.setContentID("picture.jpg");

            //正文内容部分
            MimeBodyPart text = new MimeBodyPart();
            String contextText = "亲爱的" + params.get("name") + ",祝您生日快乐";
            text.setContent(contextText + "<img src='cid:picture.jpg'>", "text/html;charset=UTF-8");

            //整合图片+正文
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(text);
            multipart.addBodyPart(image);
            multipart.setSubType(emailProperties.getSubType());

            //放入邮件中保存
            message.setContent(multipart);
            message.saveChanges();

            //6 发送邮件
            ts.sendMessage(message, message.getAllRecipients());

            //7 关闭资源
            ts.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
